package com.song.service;

import com.song.domain.Customer;
import com.song.mapper.CustomerMapper;
import com.song.mapper.OrderMapper;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ResponseStatusException;

import java.util.List;

@Service
public class CustomerService {
    private final CustomerMapper mapper;
    private final OrderMapper orderMapper;

    public CustomerService(CustomerMapper mapper, OrderMapper orderMapper) {
        this.mapper = mapper;
        this.orderMapper = orderMapper;
    }

    public Customer get(Long id) {
        return mapper.selectById(id);
    }

    public List<Customer> list(int page, int size) {
        int offset = Math.max(page - 1, 0) * size;
        return mapper.list(offset, size);
    }

    public int count() {
        return mapper.count();
    }

    public Customer create(Customer customer) {
        mapper.insert(customer);
        return customer;
    }

    public Customer update(Customer customer) {
        mapper.update(customer);
        return customer;
    }

    public void delete(Long id) {
        if (id == null) return;
        int refs = orderMapper.countByCustomerId(id);
        if (refs > 0) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "该客户已被订单引用，无法删除");
        }
        mapper.delete(id);
    }
}